package com.edu.netty.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

/**
 * <p>
 * 全局获取配置文件属性,Bean对象
 * </p>
 *
 * @author jpge
 * @since 2023-05-30
 */
@Component
@Slf4j
public class ContextHelper implements ApplicationContextAware, InitializingBean {

    public static ApplicationContext applicationContext;
    public static Environment environment;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ContextHelper.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (ObjectUtils.isEmpty(ContextHelper.environment)) {
            ContextHelper.environment = ContextHelper.applicationContext.getEnvironment();
        }
    }

    public static String getProperty(String key) {
        return ContextHelper.environment.getProperty(key);
    }

    public static <T> T getBean(String name, Class<T> type) {
        return applicationContext.getBean(name, type);
    }

    public static <T> T getBean(Class<T> type) {
        return applicationContext.getBean(type);
    }

}
